// main.js
// This file is currently empty.

const { app, BrowserWindow, BrowserView, ipcMain } = require("electron");
const path = require("path");

app.disableHardwareAcceleration();
app.commandLine.appendSwitch('ignore-gpu-blacklist');
app.commandLine.appendSwitch('disable-gpu-compositing');
app.commandLine.appendSwitch('disable-gpu-sandbox');
app.commandLine.appendSwitch('no-sandbox');

let mainWindow;
let view1;
let view2;
let contentView;
let contentViews = [];

function createWindow() {
    // 创建主窗口并最大化
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, "src/preload.js"), // Load preload.js
            contextIsolation: false,
            enableRemoteModule: false,
            nodeIntegration: true,
        },
        backgroundColor: '#ffffff',  // 设置背景色
        show: false  // 先不显示窗口
    });

    // 当窗口准备好时再显示
    mainWindow.once('ready-to-show', () => {
        mainWindow.show();
    });

    // 添加窗口大小改变事件处理
    mainWindow.on("resize", () => {
        const bounds = mainWindow.getBounds();

        // 更新 view1 的大小
        if (view1) {
            view1.setBounds({
                x: 0,
                y: 0,
                width: bounds.width,
                height: bounds.height * 0.1,
            });
        }

        // 更新 view2 的大小
        if (view2) {
            view2.setBounds({
                x: 0,
                y: view1.getBounds().height,
                width: bounds.width * 0.2,
                height: bounds.height - view1.getBounds().height,
            });
        }

        // 更新当前内容视图的大小
        if (contentView) {
            contentView.setBounds({
                x: view2.getBounds().width,
                y: view1.getBounds().height,
                width: bounds.width - view2.getBounds().width,
                height: bounds.height - view1.getBounds().height,
            });
        }
    });

    // 最大化窗口
    mainWindow.maximize();
    console.log("Main window created and maximized.");

    // 创建三个 BrowserView，添加 webPreferences
    view1 = new BrowserView({
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'src/preload.js')
        }
    });
    view2 = new BrowserView({
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'src/preload.js')
        }
    });
    console.log("View1 and View2 created.");

    // 设置 view1 的位置和大小
    mainWindow.addBrowserView(view1);
    view1.setBounds({
        x: 0,
        y: 0,
        width: mainWindow.getBounds().width,
        height: mainWindow.getBounds().height * 0.1,
    });
    console.log("View1 position and size set.");
    view1.webContents.loadFile(
        path.join(__dirname, "src/apps_quicklaunch.html")
    );

    // 设置 view2 的位置和大小
    mainWindow.addBrowserView(view2);
    view2.setBounds({
        x: 0,
        y: view1.getBounds().height,
        width: mainWindow.getBounds().width * 0.2,
        height: mainWindow.getBounds().height - view1.getBounds().height,
    });
    console.log("View2 position and size set.");
    view2.webContents.loadFile(path.join(__dirname, "src/menu.html"));

    // 创建并设置初始内容视图
    contentView = new BrowserView({
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            webSecurity: false,  // 禁用 web 安全性以允许加载远程内容
            allowRunningInsecureContent: true,
            preload: path.join(__dirname, 'src/preload.js'),
            // 添加以下配置
            javascript: true,
            plugins: true,
            experimentalFeatures: true,
            sandbox: false
        }
    });

    // 设置初始内容视图的位置和大小
    mainWindow.addBrowserView(contentView);
    const contentBounds = {
        x: view2.getBounds().width,
        y: view1.getBounds().height,
        width: mainWindow.getBounds().width - view2.getBounds().width,
        height: mainWindow.getBounds().height - view1.getBounds().height,
    };
    contentView.setBounds(contentBounds);
    console.log("Content view position and size set");

    // 设置会话配置
    const session = contentView.webContents.session;
    session.clearCache();  // 清除缓存
    session.clearStorageData();  // 清除存储数据

    // 设置请求头
    contentView.webContents.session.webRequest.onBeforeSendHeaders(
        (details, callback) => {
            callback({
                requestHeaders: {
                    ...details.requestHeaders,
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
                }
            });
        }
    );

    // 加载 URL
    contentView.webContents.loadURL('https://sso.piccltd.com.cn/login.html', {
        extraHeaders: 'pragma: no-cache\n'
    }).catch(err => {
        console.error('Failed to load URL:', err);
    });

    // 添加加载状态监听
    contentView.webContents.on('did-start-loading', () => {
        console.log('Page started loading');
    });

    contentView.webContents.on('did-stop-loading', () => {
        console.log('Page stopped loading');
    });

    contentView.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
        console.error('Page failed to load:', errorCode, errorDescription);
    });

    contentView.webContents.on('did-finish-load', () => {
        console.log('Page finished loading');
        // contentView.webContents.executeJavaScript(`
        //     console.log('Page content:', document.documentElement.innerHTML);
        // `);
    });

    contentViews.push(contentView);

    // 设置视图层级
    const views = mainWindow.getBrowserViews();
    mainWindow.setTopBrowserView(view1);
    views.forEach((view) => {
        if (view !== view1) {
            mainWindow.setTopBrowserView(view);
        }
    });

    // 打开 DevTools
    // view1.webContents.openDevTools({ mode: 'detach' });
    // view2.webContents.openDevTools({ mode: 'detach' });
    // console.log('DevTools opened for View1 and View2');

    // contentView.webContents.openDevTools({ mode: "detach" });

    // 监听页面加载完成事件
    contentView.webContents.on("did-finish-load", () => {
        const currentURL = contentView.webContents.getURL();

    });

    // 将页面逻辑抽取为函数
    function handlePageLogic(currentURL) {
        if (currentURL.includes("login.html")) {
            return `
                setTimeout(() => {
                    // 登录页面逻辑
                    if (window.location.pathname.endsWith("login.html")) {
                        const elements = document.querySelectorAll("div[onclick]");
                        elements.forEach((element) => {
                            if (element.textContent.trim() === "扫码登录") {
                                console.log("找到扫码登录按钮");
                                element.click();
                            }
                        });
                    }
                }, true);
            `;
        } else if (currentURL.includes("index.html")) {
            return `
                const appsContainer = document.getElementById('commonlyUsedApps');
                if (appsContainer) {
                    const appsList = Array.from(appsContainer.querySelectorAll('.apps-list')).map(app => {
                        const appId = app.id;
                        const link = app.querySelector('a');
                        const img = app.querySelector('img.app_img');
                        const nameDiv = app.querySelector('.apps-list-name');
                        
                        return {
                            app_id: appId,
                            app_url: link ? link.href : '',
                            icon: img ? 'https://sso.piccltd.com.cn' + img.getAttribute('src') : '',
                            app_name: nameDiv ? nameDiv.getAttribute('title') : ''
                        };
                    });
                    return appsList;
                }
                return [];
            `;
        }
        return "";
    }

    // 添加 did-frame-finish-load 事件监听
    contentView.webContents.on("did-frame-finish-load", () => {

    });

    // 修改 dom-ready 事件监听的代码
    contentView.webContents.on('dom-ready', () => {
        const currentURL = contentView.webContents.getURL();
        
        if (currentURL.includes('login.html')) {
            contentView.webContents.executeJavaScript(`
                document.body.style.pointerEvents = 'auto';
                document.documentElement.style.pointerEvents = 'auto';

                // Search and click scan login button
                const elements = document.querySelectorAll('div[onclick]');
                elements.forEach(element => {
                    if (element.textContent.trim() === '扫码登录') {
                        console.log('Found scan login button');
                        element.click();
                    }
                });
            `);
        }
    });

    // 监听页面重定向
    contentView.webContents.on("did-navigate", (event, url) => {
        console.log("Page navigated to:", url);
        
        if (url.includes('index.html')) {
            setTimeout(() => {
                contentView.webContents.executeJavaScript(`
                    console.log('Starting to parse apps list data');
                    
                    const appsContainer = document.getElementById('commonlyUsedApps');
                    console.log('Apps container:', appsContainer);
                    
                    if (appsContainer) {
                        const appElements = appsContainer.querySelectorAll('.apps-list');
                        console.log('Found apps elements count:', appElements.length);
                        
                        const appsList = Array.from(appElements).map(app => {
                            console.log('Parsing app:', app.id);
                            
                            const appId = app.id;
                            const link = app.querySelector('a');
                            const img = app.querySelector('img.app_img');
                            const nameDiv = app.querySelector('.apps-list-name');
                            
                            const appData = {
                                app_id: appId,
                                app_url: link ? new URL(link.getAttribute('href'), window.location.href).href : '',
                                icon: img ? new URL(img.getAttribute('src'), window.location.href).href : '',
                                app_name: nameDiv ? nameDiv.getAttribute('title') : ''
                            };
                            
                            console.log('Parse result:', appData);
                            return appData;
                        });
                        
                        console.log('Parsing completed, apps list:', appsList);
                        
                        if (appsList.length > 0) {
                            window.electronAPI.sendToMain('parsed-apps-data', appsList);
                            console.log('Data sent to main process');
                        } else {
                            console.log('No app data found');
                        }
                    } else {
                        console.log('Apps container element not found');
                    }
                `, true).catch(err => {
                    console.error('Error executing JavaScript:', err);
                });
            }, 2000);
        }
    });

    // 监听从渲染进程发送的应用数据
    ipcMain.on('parsed-apps-data', (event, appData) => {
        console.log('Received parsed apps data:', appData);
        
        if (!appData || appData.length === 0) {
            console.log('Received app data is empty');
            return;
        }
        
        // 发送数据到 view1
        if (view1 && view1.webContents) {
            try {
                console.log('Sending app data to view1:', JSON.stringify(appData));
                view1.webContents.send('app-data', appData);
                console.log('App data sent to view1');
                
                // 查找并自动打开指定的应用
                const targetApp = appData.find(app => app.app_id === '5cd144e926914112f6cdb43a');
                if (targetApp) {
                    console.log('Auto opening target app:', targetApp.app_name);
                    // 创建新的浏览器视图来打开目标应用
                    const newView = new BrowserView({
                        webPreferences: {
                            nodeIntegration: false,
                            contextIsolation: true,
                            webSecurity: false,
                            allowRunningInsecureContent: true,
                            preload: path.join(__dirname, 'src/preload.js')
                        }
                    });

                    // 设置新视图的位置和大小
                    mainWindow.addBrowserView(newView);
                    const contentBounds = {
                        x: view2.getBounds().width,
                        y: view1.getBounds().height,
                        width: mainWindow.getBounds().width - view2.getBounds().width,
                        height: mainWindow.getBounds().height - view1.getBounds().height,
                    };
                    newView.setBounds(contentBounds);

                    // 加载目标应用的 URL
                    newView.webContents.loadURL(targetApp.app_url);

                    // 更新当前内容视图
                    if (contentView) {
                        mainWindow.removeBrowserView(contentView);
                    }
                    contentView = newView;
                    contentViews.push(newView);
                }

                // 触发 view1 刷新
                view1.webContents.executeJavaScript(`
                    console.log('Received data in view1:', ${JSON.stringify(appData)});
                    if (typeof updateAppsList === 'function') {
                        console.log('Calling updateAppsList');
                        updateAppsList(${JSON.stringify(appData)});
                    } else {
                        console.log('updateAppsList function not found');
                        window.dispatchEvent(new CustomEvent('apps-data-updated'));
                    }
                `).catch(err => {
                    console.error('Error executing JavaScript in view1:', err);
                });
            } catch (error) {
                console.error('Error sending app data to view1:', error);
            }
        } else {
            console.error('view1 or its webContents is not available');
        }
    });

    // 监听窗口关闭事件
    mainWindow.on("closed", function () {
        mainWindow = null;
    });

    contentView.webContents.on('console-message', (event, level, message) => {
        console.log('Console message from web page:', message);
    });
}

function createNewTab(url) {
    console.log("Creating new tab for URL:", url);

    const newView = new BrowserView();
    newView.webContents.loadURL(url);
    views.push({ view: newView, url: url });
    switchToView(views.length - 1);
    setupViewEventListeners(newView);
    updateMenu();
    console.log("New tab created successfully");

    // Send app data to apps_quicklaunch.html
    const appsData = [
        {
            url: "https://www.baidu.com",
            icon: "path/to/icon1.png",
            app_name: "Baidu",
            app_id: "app1",
        },
        {
            url: "https://www.bing.com",
            icon: "path/to/icon2.png",
            app_name: "Bing",
            app_id: "app2",
        },
        // Add more apps as needed
    ];
    view1.webContents.send("apps-data", appsData);
}

// 处理新建内容视图的请求
ipcMain.on("create-new-browser-view", (event, url) => {
    console.log("Creating new browser view for:", url);

    // 添加 URL 验证
    if (!url) {
        console.error("Invalid URL provided");
        return;
    }

    // 创建新的内容视图
    const newView = new BrowserView({
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'src/preload.js')
        }
    });

    // 设置新视图的位置和大小（与原内容视图相同）
    mainWindow.addBrowserView(newView);
    const contentBounds = {
        x: view2.getBounds().width,
        y: view1.getBounds().height,
        width: mainWindow.getBounds().width - view2.getBounds().width,
        height: mainWindow.getBounds().height - view1.getBounds().height,
    };
    newView.setBounds(contentBounds);

    try {
        // 加载请求的 URL
        newView.webContents.loadURL(url);
    } catch (error) {
        console.error("Error loading URL:", error);
        return;
    }

    // 隐藏当前内容视图
    if (contentView) {
        mainWindow.removeBrowserView(contentView);
    }

    // 更新当前内容视图
    contentView = newView;
    contentViews.push(newView);

    // 设置视图层级
    const views = mainWindow.getBrowserViews();
    mainWindow.setTopBrowserView(view1);
    views.forEach((view) => {
        if (view !== view1) {
            mainWindow.setTopBrowserView(view);
        }
    });

    console.log("New browser view created and displayed");
});

app.on("ready", createWindow);

app.on("window-all-closed", function () {
    if (process.platform !== "darwin") {
        app.quit();
    }
});

app.on("activate", function () {
    if (mainWindow === null) {
        createWindow();
    }
});
